/*
    hdvb - Framework for sophisticated DVB applications
    Copyright (C) 2012 Tony Houghton <h@realh.co.uk>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/* Converts all strings in an EIT database to UTF-8. */

#include <glib.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <hdvb/cacheddb.h>
#include <hdvb/dbcommon.h>
#include <hdvb/eitdb.h>

typedef struct {
    int event_id;
    int service_id;
    char *event_name;
    char *event_text;
} EventDetails;

static gboolean
decode_database(const char *filename)
{
    HdvbCachedDb *cdb = hdvb_cached_db_open(filename, TRUE, FALSE, NULL,
            HDVB_EIT_DB_VERSION, NULL);
    sqlite3_stmt *stmt;
    GArray *events;
    int result;
    int n;
    /* HdvbEitDbDecoder decoder; */

    if (!cdb)
        return FALSE;
    if (!hdvb_eit_db_setup_decoder(cdb->db))
        return FALSE;
    /* decoder = hdvb_eit_db_get_decoder(cdb->db); */
    events = g_array_new(FALSE, FALSE, sizeof(EventDetails));
    stmt = hdvb_db_prepare_statement(cdb->db,
            "SELECT event_id, service_id, "
                "hdvb_decode(event_name), hdvb_decode(event_text) "
                "FROM short_descriptors");
    /*
    stmt = hdvb_db_prepare_statement(cdb->db,
            "SELECT event_id, service_id, event_name, event_text "
                "FROM short_descriptors");
    */
    if (!stmt)
        return FALSE;
    while ((result = hdvb_db_step(stmt)) == SQLITE_ROW)
    {
        EventDetails e;

        e.event_id = sqlite3_column_int(stmt, 0);
        e.service_id = sqlite3_column_int(stmt, 1);
        e.event_name = g_strdup((const char *) sqlite3_column_text(stmt, 2));
        e.event_text = g_strdup((const char *) sqlite3_column_text(stmt, 3));
        /*
        e.event_name = decoder(sqlite3_column_blob(stmt, 2),
                sqlite3_column_bytes(stmt, 2));
        e.event_text = decoder(sqlite3_column_blob(stmt, 3),
                sqlite3_column_bytes(stmt, 3));
        */
        if (e.event_name || e.event_text)
        {
            events = g_array_append_val(events, e);
        }
    }
    if (result != SQLITE_DONE)
    {
        return FALSE;
    }
    sqlite3_finalize(stmt);
    stmt = hdvb_db_prepare_statement(cdb->db,
            "UPDATE short_descriptors "
                "SET event_name = ?, event_text = ? "
                "WHERE event_id = ? AND service_id = ?");
    if (!stmt)
    {
        return FALSE;
    }
    g_debug("Replacing strings in %d events", events->len);
    for (n = 0; n < events->len; ++n)
    {
        EventDetails *e = &g_array_index(events, EventDetails, n);

        sqlite3_bind_text(stmt, 1, e->event_name, -1, g_free);
        sqlite3_bind_text(stmt, 2, e->event_text, -1, g_free);
        sqlite3_bind_int(stmt, 3, e->event_id);
        sqlite3_bind_int(stmt, 4, e->service_id);
        if (hdvb_db_step(stmt) != SQLITE_DONE)
            return FALSE;
        sqlite3_reset(stmt);
    }
    sqlite3_finalize(stmt);
    g_debug("Updating encoding info table");
    if (!hdvb_db_exec(cdb->db,
            "INSERT OR REPLACE INTO encoding (encoding) VALUES ('utf8')"))
    {
        return FALSE;
    }
    g_debug("Syncing");
    return hdvb_cached_db_sync(cdb);
}

int
main(int argc, char **argv)
{
    gboolean usage = FALSE;
    gboolean err = FALSE;

    if (argc != 2)
    {
        usage = TRUE;
        err = TRUE;
    }
    else if (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h") ||
            !strcmp(argv[1], "--usage"))
    {
        usage = TRUE;
    }
    else if (!g_file_test(argv[1], G_FILE_TEST_EXISTS))
    {
        usage = TRUE;
        err = TRUE;
    }
    if (usage)
    {
        fprintf(stderr, "Usage: hdvb-epgdecode FILENAME\n"
                "Decodes all the strings (converts to UTF-8) in the hdvb\n"
                "EIT sqlite3 database FILENAME\n");
        exit(err = TRUE);
    }
    return decode_database(argv[1]) != TRUE;
}
